package com.example.demo.bis.websocket.controller;

import com.example.demo.bis.websocket.service.WebSocketService;
import com.example.demo.demos.websocket.AuthWebSocketHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author lyh
 * @date 2025/7/21 17:00
 */
@Api(tags = "WebSocket主动发送消息")
@RestController
public class WebSocketController {

    @Resource
    private WebSocketService webSocketService;

    @ApiOperation("获取所有已连接客户端的IP地址")
    @GetMapping("/connectedIps")
    public List<String> getConnectedClientIps() {
        return webSocketService.getAllConnectedClientIps();
    }

    // 发送消息给所有连接者
    @ApiOperation("发送消息给所有连接者")
    @ApiImplicitParam(paramType = "query", name = "message", value = "消息内容")
    @GetMapping("/push")
    public String pushMessage(@RequestParam String message) throws IOException {
        webSocketService.broadcastToAll("TEST_INFO", message);
        return "消息发送成功";
    }

    @ApiOperation("向指定IP列表发送消息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "ips", value = "目标IP地址列表（逗号分隔）", required = true, example = "192.168.1.1,192.168.1.2"),
            @ApiImplicitParam(paramType = "query", name = "message", value = "消息内容", required = true)
    })
    @GetMapping("/pushToIps")
    public String pushMessageToIps(@RequestParam String ips, @RequestParam String message) {
        List<String> ipList = Arrays.asList(ips.split(","));
        webSocketService.sendToIps(ipList, "TARGETED_MSG", message);
        return "消息已发送到指定IP客户端";
    }
}
